import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
import axios from 'axios'

axios.defaults.baseURL = "http://bugtracker.itsource.cn:8080"
Vue.prototype.$http = axios
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
import routes from './routes'
import Mock from './mock'
// Mock.bootstrap();
// import 'font-awesome/css/font-awesome.min.css'
import '@/common/js/permission'
Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

//NProgress.configure({ showSpinner: false });

const router = new VueRouter({
    routes
})

//处理页面刷新动态路由失效问题
initIndexRouters();

// 动态路由
function initIndexRouters() {
    if (!localStorage.menus) {
        return;
    }
    //防止重复配置路由：5就是main.js中路由的个数 - 如果你的静态路由是6个这里要写成6
    if (router.options.routes.length > 8) {
        return;
    }
    let menus = localStorage.getItem('menus');
    menus = JSON.parse(menus);
    let tempRouters = [];
    menus.forEach(menu => {
        let indexRouter = {
            path: '/',
            iconCls: menu.icon,
            name: menu.name,
            component: resolve => require(['@/views/Home'], resolve),
            children: []
        }
        menu.children.forEach(cMenu => {
            let cr = {
                path: cMenu.url,
                name: cMenu.name,
                component: resolve => require(['@/views/' + cMenu.component], resolve)
            }
            indexRouter.children.push(cr)
        })
        tempRouters.push(indexRouter)
        router.options.routes.push(indexRouter)
    })
    //动态路由配置
    router.addRoutes(tempRouters);
}


// 1.配置路由拦截器，作用是判断当前用户是否登录如果没有那么跳转到login页面
router.beforeEach((to, from, next) => {
    console.log("1111111111");
    if (to.path == '/login' || to.path == '/shopRegister') {
        if (localStorage.getItem("token")) {
            // 1.如果访问的是登录页面或者是店铺入驻页面，那么清除缓存中的用户信息
            localStorage.removeItem('logininfo');
            localStorage.removeItem('token');
            localStorage.removeItem('permissions');
            localStorage.removeItem('menus');
            // 2.清除浏览器路由缓存
            location.reload();
        }
        next();
    } else {
        let logininfo = JSON.parse(localStorage.getItem('logininfo'));
        if (logininfo) {
            next()
        } else {
            next({path: '/login'})
        }
    }
})
//2.配置axios前置拦截器，作用是让所有axios请求携带token，后台需要token校验是否登录
axios.interceptors.request.use(config => {
    console.log("222222222");
    // 2.1.从缓存中获取到token
    let token = localStorage.getItem("token");
    // 2.2.如果token不为null，那么设置到请求头中，此处哪怕为null，我们也不进行处理，因为后台会进行拦截
    if (token) {
        config.headers['token'] = token;
    }
    // 2.3.放行
    return config;
}, error => {
    Promise.reject(error);
})

//3.配置axios后置拦截器，作用是为了得到后端的拦截器响应结果
//  前端需要知道用户是否登录，如果响应是success=false&resultObj=noLogin那么说明用户未登录，直接跳转到登录页面
axios.interceptors.response.use(result => {
    console.log("333333333");
    // 3.1.获取到后端的响应结果
    let data = result.data;
    // 3.2.判断如果后端响应是success=false&resultObj=noLogin，那就说明在后端拦截器中被拦截下来了，那么跳转到登录页面
    if (!data.success && data.resultObj === "noLogin") {
        // 跳转登录页面
        router.push({path: '/login'});
    }
    if (!data.success && data.resultObj === "noPermission") {
        // 跳转登录页面
        router.push({path: '/noPermission'});
    }
    // 3.3.放行
    return result;
}, error => {
    Promise.reject(error);
})

//router.afterEach(transition => {
//NProgress.done();
//});

new Vue({
    //el: '#app',
    //template: '<App/>',
    router,
    store,
    //components: { App }
    render: h => h(App)
}).$mount('#app')

